package com.github.wxiaoqi.security.crm.core.biz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.auth.common.util.jwt.IJWTInfo;
import com.github.wxiaoqi.security.auth.common.util.jwt.JWTHelper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.crm.request.QueryMerchantBaseListRequest;
import com.github.wxiaoqi.security.common.enums.UserTypeEnums;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.crm.core.client.FeignAdminClient;
import com.github.wxiaoqi.security.crm.core.entity.PlatformBase;
import com.github.wxiaoqi.security.crm.core.mapper.PlatformBaseMapper;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 平台基础信息
 *
 * @author centerroot
 * @email ${email}
 * @date 2018-07-16 10:15:48
 */
@Service
public class PlatformBaseBiz extends BaseBiz<PlatformBaseMapper,PlatformBase> {
	
	@Autowired
	private FeignAdminClient feignRoleClient;
    @Autowired
    private UserAuthConfig userAuthConfig;
	/**
	 * 添加
	 */
	public void addPlatform(PlatformBase entity) {
		Map<String, Object> result = new HashMap<String, Object>();
		//添加平台
		long platformId = SnowFlake.getId();
		entity.setPlatformId(String.valueOf(platformId));
		entity.setAuthenticationStatus("00");//第一次添加都是"未认证状态"
		mapper.insert(entity);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("platformName", entity.getPlatformName());
		map.put("platformId", entity.getPlatformId());
		map.put("type", UserTypeEnums.PLATFORM_ADMIN.getCode());
		map.put("token", entity.getToken());
		this.commonAdd(map);
	}
	/**
	 * 添加商户与平台公共方法
	 * 添加平台需传参数 ： platformName，platformId，type为2（int），token
	 * 添加商户需传参数 ： merchantName，merchantId，platformId，type为3（int），token
	 * @param param
	 */
	public void commonAdd(Map<String, Object> param) {
		String platformName = (String) param.get("platformName");
		String merchantName = (String) param.get("merchantName");
		String platformId = (String) param.get("platformId");
		String merchantId = (String) param.get("merchantId");
		Integer type = (Integer) param.get("type");
		String token = (String) param.get("token");
		String userNo = null;
		String userName = null;
		try {
			IJWTInfo info = JWTHelper.getInfoFromToken(token, userAuthConfig.getPubKeyByte());
			userNo = info.getId();
			userName = info.getName();
		} catch (Exception e) {
			e.printStackTrace(); 
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		//dept表添加
		Map<String, Object> deptMap = new HashMap<String, Object>();
		deptMap.put("platformId", Long.valueOf(platformId));
		//如果是平台，平台的父级固定是 海盗集团，id为1，如果修改了最高级目录则要修改修改此处值
		Integer parentId = 1;
		//根据平台编号获取父机构编号
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() != type){
			Map<String, Object> deptPMap = new HashMap<String, Object>();
			deptPMap.put("parentId", 1);
			deptPMap.put("platformId",Long.valueOf(platformId));
			Map<String, Object> deptPResultMap = feignRoleClient.selectByPlatformId(deptPMap);
			String deptPResultCode = (String) deptPResultMap.get("code");
			if(!ResponseCode.OK.getCode().equals(deptPResultCode)){
		    	result.put("code", deptPResultMap.get("code"));
		    	result.put("msg", deptPResultMap.get("msg"));
		    	result.put("success", false);
			}
			Map<String, Object> mapDept = (Map<String, Object>) deptPResultMap.get("dept");
			Integer deptId = (Integer) mapDept.get("id");
			parentId = deptId;
			
		}
		deptMap.put("parentId", parentId);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			deptMap.put("name", platformName);
		}else {
			deptMap.put("name", merchantName);
		}
		
		deptMap.put("delFlag", "0");
		Map<String, Object> deptResultMap = feignRoleClient.addDept(deptMap);
		String deptCode = (String) deptResultMap.get("code");
		if(!ResponseCode.OK.getCode().equals(deptCode)){
	    	result.put("code", deptResultMap.get("code"));
	    	result.put("msg", deptResultMap.get("msg"));
	    	result.put("success", false);
		}
		Integer deptId = (Integer) deptResultMap.get("deptId");
		//添加角色
		Map<String, Object> roleMap = new HashMap<String, Object>();
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			roleMap.put("roleName", platformName + "平台管理员");
		}else {
			roleMap.put("roleName", merchantName + "商户管理员");
		}
		
		roleMap.put("remark", "创建平台自动生成角色");
		roleMap.put("deptId", deptId);
		roleMap.put("platformId", platformId);
		roleMap.put("isDelete", 1);
		Map<String, Object> roleResultMap = feignRoleClient.addRole(roleMap);
		Integer roleId = (Integer) roleResultMap.get("roleId");
		//添加用户
		Map<String, Object> userMap = new HashMap<String, Object>();
		userMap.put("userId", SnowFlake.getId());
		userMap.put("crtUser", userNo);
		userMap.put("crtName", userName);
		userMap.put("updUser", userNo);
		userMap.put("updName", userName);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("username", platformName);
		}else {
			userMap.put("username", merchantName);
		}
		//默认密码123456
		userMap.put("password", "123456");
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("name", platformName);
		}else {
			userMap.put("name", merchantName);
		}
		userMap.put("deptId", deptId);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("deptName", platformName);
		}else {
			userMap.put("deptName", merchantName);
		}
		userMap.put("description", "添加平台自动添加的平台管理员");
		//userMap.put("crtTime", new Date());
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() != type){
			userMap.put("merchantId", merchantId);
		}
		userMap.put("platformId", platformId);
		if(UserTypeEnums.PLATFORM_ADMIN.getCode() == type){
			userMap.put("userType", UserTypeEnums.PLATFORM_ADMIN.getCode());
		}else {
			userMap.put("userType", UserTypeEnums.MERCHANT_ADMIN.getCode());
		}
		
		Map<String, Object> userResultMap = feignRoleClient.addUser(userMap);
		Long userId = (Long) userResultMap.get("userId");
		//添加关系
		Map<String, Object> userRoleMap = new HashMap<String, Object>();
		userRoleMap.put("userId", userId);
		userRoleMap.put("roleId", roleId);
		Map<String, Object> userRoleResultMap = feignRoleClient.addUserRole(userRoleMap);
		//资源
		Map<String, Object> resourceAuthorityMap = new HashMap<String, Object>();
		resourceAuthorityMap.put("roleId", roleId);
		Map<String, Object> resourceAuthorityResultMap = feignRoleClient.platformAuthority(resourceAuthorityMap);
	}
	 public TableResultResponse<PlatformBase> pageList(QueryMerchantBaseListRequest bean){
		 Example example = new Example(PlatformBase.class);
		 Criteria criteria = example.createCriteria();
		 example.setOrderByClause("create_time desc");
		 Page<PlatformBase> result = PageHelper.startPage(bean.getPage(), bean.getLimit());
		 List<PlatformBase> list = mapper.selectByExample(example);
		 return new TableResultResponse<PlatformBase>(result.getTotal(), list);
	 }
}